import torch
import torch.nn as nn
import torchvision

import models.conv_type
from utils.builder import Builder


def _make_divisible(v, divisor, min_value=None):
    """
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    :param v:
    :param divisor:
    :param min_value:
    :return:
    """
    if min_value is None:
        min_value = divisor
    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
    # Make sure that round down does not go down by more than 10%.
    if new_v < 0.9 * v:
        new_v += divisor
    return new_v


def first_conv_3x3_bn(inp, oup, stride):
    return nn.Sequential(
        nn.Conv2d(inp, oup, kernel_size=3, stride=stride, padding=1, bias=False),
        nn.BatchNorm2d(oup),
        nn.Hardswish(inplace=True)
    )


class SELayer(nn.Module):
    def __init__(self, builder, channel, reduction=4):
        super(SELayer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            builder.conv1x1(channel, _make_divisible(channel // reduction, 8), bias=True),
            nn.ReLU(inplace=True),
            builder.conv1x1(_make_divisible(channel // reduction, 8), channel, bias=True),
            nn.Hardswish(inplace=True)
        )

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x)
        y = self.fc(y)
        return x * y


def conv_1x1_bn(builder, inp, oup):
    return nn.Sequential(
        builder.convbn1x1(inp, oup),
        nn.Hardswish(inplace=True)
    )


class InvertedResidual(nn.Module):
    def __init__(self, builder, inp, hidden_dim, oup, kernel_size, stride, use_se, use_hs):
        super(InvertedResidual, self).__init__()
        assert stride in [1, 2]

        self.identity = stride == 1 and inp == oup

        if inp == hidden_dim:
            self.conv = nn.Sequential(
                # dw
                nn.Conv2d(hidden_dim, hidden_dim, kernel_size, stride, (kernel_size - 1) // 2, groups=hidden_dim,
                          bias=False),
                nn.BatchNorm2d(hidden_dim),
                nn.Hardswish(inplace=True) if use_hs else nn.ReLU(inplace=True),
                # Squeeze-and-Excite
                SELayer(builder, hidden_dim) if use_se else nn.Identity(),
                # pw-linear
                builder.convbn1x1(hidden_dim, oup)
            )
        else:
            self.conv = nn.Sequential(
                # pw
                builder.convbn1x1(inp, hidden_dim),
                nn.Hardswish(inplace=True) if use_hs else nn.ReLU(inplace=True),
                # dw
                nn.Conv2d(hidden_dim, hidden_dim, kernel_size, stride, (kernel_size - 1) // 2, groups=hidden_dim,
                          bias=False),
                nn.BatchNorm2d(hidden_dim),
                # Squeeze-and-Excite
                SELayer(builder, hidden_dim) if use_se else nn.Identity(),
                nn.Hardswish(inplace=True) if use_hs else nn.ReLU(inplace=True),
                # pw-linear
                builder.convbn1x1(hidden_dim, oup)
            )

    def forward(self, x):
        if self.identity:
            return x + self.conv(x)
        else:
            return self.conv(x)


class MobileNetV3(nn.Module):
    def __init__(self, builder, cfgs, mode, num_classes=1000, width_mult=1.):
        super(MobileNetV3, self).__init__()
        # setting of inverted residual blocks
        self.cfgs = cfgs
        assert mode in ['large', 'small']

        # building first layer
        input_channel = _make_divisible(16 * width_mult, 8)
        layers = [first_conv_3x3_bn(3, input_channel, 2)]
        # building inverted residual blocks
        block = InvertedResidual
        for k, t, c, use_se, use_hs, s in self.cfgs:
            output_channels = _make_divisible(c * width_mult, 8)
            last_output_channels = _make_divisible(input_channel * t, 8)
            layers.append(block(builder, input_channel, last_output_channels, output_channels, k, s, use_se, use_hs))
            input_channel = output_channels
        self.features = nn.Sequential(*layers)

        # building last several layers
        self.conv = conv_1x1_bn(builder, input_channel, last_output_channels)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        output_channels_dict = {'large': 1280, 'small': 1024}
        output_channels = output_channels_dict[mode]
        output_channels = _make_divisible(output_channels * width_mult, 8) if width_mult > 1.0 else output_channels
        self.classifier = nn.Sequential(
            nn.Linear(last_output_channels, output_channels),
            nn.Hardswish(inplace=True),
            nn.Linear(output_channels, num_classes),
        )
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode="fan_out")
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.ones_(m.weight)
                nn.init.zeros_(m.bias)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.zeros_(m.bias)

    def forward(self, x):
        x = self.features(x)
        x = self.conv(x)
        x = self.avgpool(x).flatten(1)
        x = self.classifier(x)
        return x


def mobilenet_v3_large(pretrained=False, builder=None, num_classes=1000):
    if pretrained:
        pass
    """
    Constructs a MobileNetV3-Large model
    """
    cfgs = [
        # k, t, c, SE, HS, s
        [3, 1, 16, 0, 0, 1],
        [3, 4, 24, 0, 0, 2],
        [3, 3, 24, 0, 0, 1],
        [5, 3, 40, 1, 0, 2],
        [5, 3, 40, 1, 0, 1],
        [5, 3, 40, 1, 0, 1],
        [3, 6, 80, 0, 1, 2],
        [3, 2.5, 80, 0, 1, 1],
        [3, 2.3, 80, 0, 1, 1],
        [3, 2.3, 80, 0, 1, 1],
        [3, 6, 112, 1, 1, 1],
        [3, 6, 112, 1, 1, 1],
        [5, 6, 160, 1, 1, 2],
        [5, 6, 160, 1, 1, 1],
        [5, 6, 160, 1, 1, 1]
    ]
    return MobileNetV3(builder, cfgs, mode='large', num_classes=num_classes)


def mobilenet_v3_small(pretrained=False, builder=None, num_classes=1000):
    if pretrained:
        pass
    """
    Constructs a MobileNetV3-Small model
    """
    cfgs = [
        # k, t, c, SE, HS, s
        [3, 1, 16, 1, 0, 2],
        [3, 4.5, 24, 0, 0, 2],
        [3, 3.67, 24, 0, 0, 1],
        [5, 4, 40, 1, 1, 2],
        [5, 6, 40, 1, 1, 1],
        [5, 6, 40, 1, 1, 1],
        [5, 3, 48, 1, 1, 1],
        [5, 3, 48, 1, 1, 1],
        [5, 6, 96, 1, 1, 2],
        [5, 6, 96, 1, 1, 1],
        [5, 6, 96, 1, 1, 1],
    ]

    return MobileNetV3(builder, cfgs, mode='small', num_classes=num_classes)


def mobilenet_v3_small_dense(pretrained=False, num_classes=1000):
    conv_bn_layer = getattr(models.conv_type, "DenseConv2dBN")
    nonlinearity = 'relu'
    builder = Builder(conv_bn_layer=conv_bn_layer, nonlinearity=nonlinearity)
    model = mobilenet_v3_small(pretrained, builder, num_classes=num_classes)
    return model


def mobilenet_v3_large_dense(pretrained=False, num_classes=1000):
    conv_bn_layer = getattr(models.conv_type, "DenseConv2dBN")
    nonlinearity = 'relu'
    builder = Builder(conv_bn_layer=conv_bn_layer, nonlinearity=nonlinearity)
    model = mobilenet_v3_large(pretrained, builder, num_classes=num_classes)
    return model


if __name__ == '__main__':
    conv_bn_layer = getattr(models.conv_type, "DenseConv2dBN")
    nonlinearity = 'relu'
    data = torch.ones([1, 3, 224, 224], dtype=torch.float32)
    builder = Builder(conv_bn_layer=conv_bn_layer, nonlinearity=nonlinearity)
    model1 = mobilenet_v3_small(builder=builder, num_classes=1000)
    model2 = torchvision.models.mobilenet_v3_small()
    model1.eval()
    model2.eval()
    state_dict = {}
    print(sum([p.numel() for p in model1.parameters()]))
    print(sum([p.numel() for p in model2.parameters()]))

    for (key1, value1), (key2, value2) in zip(model1.state_dict().items(), model2.state_dict().items()):
        state_dict[key2] = value1.clone()
        assert value1.shape == value2.shape
    model2.load_state_dict(state_dict)
    output1 = model1(data)
    output2 = model2(data)
    print(torch.allclose(output1, output2))
